var map;
var itinerary;
var itineraryLineColor = "#3355ff";
var itineraryPoints    = [];
var markers            = [];

$(function()
{
  map = new GMap2($("#map")[0], {draggableCursor:'auto', draggingCursor:'move'});
  map.setCenter(new GLatLng(48.86, 2.35), 15);
  map.addMapType(G_PHYSICAL_MAP);
  map.addControl(new GMapTypeControl());
  map.addControl(new GSmallZoomControl());
  
  // Configure Google Maps mouse interaction
  map.disableDoubleClickZoom();
  map.enableScrollWheelZoom();
  GEvent.addListener(map, "click", leftClick);
});

$(window).unload(GUnload);

function addIcon(icon)
{
  // Configure an icon's attributes
  icon.iconSize      = new GSize(11, 11);
  icon.dragCrossSize = new GSize(15, 15);
  icon.shadowSize    = new GSize(11, 11);
  icon.iconAnchor    = new GPoint(5, 5);
}

function leftClick(overlay, point)
{
  if (point) {
    // Square marker icons
    var square = new GIcon();
    square.image = "/media/img/square.png";
    addIcon(square);
    
    // Make markers draggable
    var marker = new GMarker(point, {icon:square, draggable:true, bouncy:true, dragCrossMove:true});
    markers.push(marker);
    map.addOverlay(marker);
    
    GEvent.addListener(marker, "drag", drawItinerary);
    
    GEvent.addListener(marker, "mouseover", function()
      {
        marker.setImage("/media/img/square-hover.png");
      });
    
    GEvent.addListener(marker, "mouseout", function()
      {
        marker.setImage("/media/img/square.png");
      });
    
    // Second click listener to remove the square
    GEvent.addListener(
      marker, "click",
      function()
      {
        // Find out which square to remove
        for(var n = 0; n < markers.length; n++) {
          if (markers[n] == marker) {
            map.removeOverlay(markers[n]);
            break;
          }
        }
      
        markers.splice(n, 1);
        drawItinerary();
      });

    drawItinerary();
  }
}

function drawItinerary()
{
  if (itinerary) {
    map.removeOverlay(itinerary);
  }
  
  itineraryPoints.length = 0;

  for (i = 0; i < markers.length; i++) {
    itineraryPoints.push(markers[i].getLatLng());
  }
  
  itinerary = new GPolyline(itineraryPoints, itineraryLineColor, 3, .8);
  
  map.addOverlay(itinerary);
}

function zoomToItinerary()
{
  if (itinerary && itineraryPoints.length > 0) {
    var bounds = itinerary.getBounds();
    map.setCenter(bounds.getCenter());
    map.setZoom(map.getBoundsZoomLevel(bounds));
  }
}

function clearItinerary()
{
  // Remove itinerary and reset arrays
  map.clearOverlays();
  itineraryPoints.length = 0;
  markers.length = 0;
}

function editItinerary(id)
{
  $('.editColumn').empty();
  $('#edit-' + id).html('X');
  
  $.getJSON(
    '/track/ajax/checkpoints/' + id + '/',
    function (data)
    {
      clearItinerary();
      
      $.each(
        data,
        function()
        {
          leftClick(undefined, new GPoint(this[0], this[1]));
        })
      
      zoomToItinerary();
      
      $('#save').unbind('click').click(saveItinerary(id)).attr('disabled', false);
    });
}

function saveItinerary(id)
{
  return function()
  {
    $.post(
      '/track/itinerary/save/' + id + '/',
      {checkpoints: itineraryPoints},
      function()
      {
        alert('Itinerary ' + id + ' saved !');
      });
  };
}
